
// #include "complib/include/comp_api.h"

#include "igmp_pkt_process/igmp_pkt_process.h"
#include "multicast_ctr_init/multicast_ctr_init.h"
#include "register_init_cfg/register_init.h"
#include "timer_func/timer_func.h"

void create_debug_file()
{
  FILE *fp;
  char str[] = "****** debug message ******\n";
  fp = fopen("debug_log.txt", "w");
  fwrite(str, sizeof(char), strlen(str), fp);
  fclose(fp);
  return;
}

int main(int argc, char *argv[])
{
  setbuf(stdout, NULL);

  int ret = 0;
  struct timeval tv_current; // 记录当前的时间
  u64 cur_time_count_ns = 0; // 单位为ns
  u16 multicast_mid = 8;

  u8 *pkt = NULL; // 用于指针接收报文
  u16 pkt_len = 0;

  // 初始化进程
  char test_rule[64] = {0};
  char temp_net_interface[16] = {0};

  u32 sw_version = 0x20240224;

  if (argc != 2)
  {
    printf("input format:./multicast net_interface\n");
    return 0; // 调试注释掉
  }

  // libpcap initialization
  sprintf(temp_net_interface, "%s", argv[1]);

  create_debug_file();

  tunnel_pkt_malloc();

  // 进入网络初始化状态
  ret = multicast_ctr_init(temp_net_interface, &multicast_mid, sw_version);
  if (ret == -1)
  {
    printf("multicast_ctr_init fail\n");
    return 0;
  }

  // 进入静态组播配置阶段
  ret = register_init_cfg();
  if (ret == -1)
  {
    printf("static_mac_cfg fail\n");
    return 0;
  }

  while (1)
  {
    cur_time_count_ns = get_cur_nano_sec(); // 获取当前系统时间

    if (cur_time_count_ns != 0)
    {
      ret = timer_func(cur_time_count_ns); // 超时处理函数
      if (ret == -1)
        return 0;
    }

    pkt = tsmp_pkt_receive_dispatch_1((u16 *)&pkt_len); // 非阻塞接收报文

    if (pkt == NULL)
    {
      continue;
    }
    else if (pkt[12] == 0xff && pkt[13] == 0x01) // 判断是否为TSMP报文，以太网类型为0xff01
    {
      ret = igmp_pkt_process(pkt, pkt_len - sizeof(tsmp_header)); // 对报文进行处理

      if (ret == -1)
      {
        printf("igmp_pkt_process, error! \n");
        return -1;
      }
    }
  }

  igmp_free();
  tunnel_pkt_free();
  resource_clear(temp_net_interface);

  return 0;
}
